﻿using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Principal;
using System.ServiceModel;
using YBBEST.Office365Portal.Core.SPCopyWS;

namespace YBBEST.Office365Portal.Core
{
    public interface ICopyRepository
    {
        bool UpLoadFile(string fileName, string destinationUrls, byte[] fileData);
    }

    public class CopyRepository : ICopyRepository
    {
        private readonly IProxyConfiguration configuration;
        private readonly IServiceConnection serviceConnection;
        private readonly string listsAsmxEndpoint;

        public CopyRepository(IProxyConfiguration configuration, IServiceConnection serviceConnection)
        {
            this.configuration = configuration;
            this.serviceConnection = serviceConnection;
            listsAsmxEndpoint = string.Format("{0}_vti_bin/Copy.asmx", configuration.SiteUrl);
        }

        /// <summary>
        /// Uploads the file.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="destinationUrl">The destination URL.</param>
        /// <param name="fileData">The file data.</param>
        /// <returns></returns>
        public bool UpLoadFile(string fileName,string destinationUrl, byte[] fileData )
        {
            FieldInformation[] fieldInformations = configureFileMetaFields(fileName).ToArray();
            var destinationUrls=new[]{configuration.SiteUrl+destinationUrl+"/"+fileName};
            serviceConnection.ConfigureAuthenticationRequestCookie();
            CopyResult[] copyResults;
            using (var proxy = new CopySoapClient())
            {
                serviceConnection.SetEndpoint(proxy,listsAsmxEndpoint);
                if (proxy.ClientCredentials != null)
                {
                    proxy.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
                    proxy.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
                }
                using (new OperationContextScope(proxy.InnerChannel))
                {
                    serviceConnection.SetOutgoingMessageProperties();
                    
                    proxy.CopyIntoItems(fileName, destinationUrls, fieldInformations, fileData, out copyResults);
                }
            }
            return copyResults != null && copyResults.All(cr => cr.ErrorCode == CopyErrorCode.Success);
        }

        private IEnumerable<FieldInformation> configureFileMetaFields(string fileName)
        {
            return new List<FieldInformation>
            {
                new FieldInformation
                {
                    DisplayName = "Title",
                    InternalName = "Title",
                    Value = fileName,
                    Type = FieldType.Text
                }
            };
        }
    }
}